package com.apartment.own.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.apartment.common.core.domain.AjaxResult;
import com.apartment.common.exception.CustomException;
import com.apartment.common.utils.CollectionHelper;
import com.apartment.common.utils.DateUtils;
import com.apartment.common.utils.StringUtils;
import com.apartment.own.domain.OwnCategoryEntity;
import com.apartment.own.request.res.ResArticleDTO;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apartment.own.mapper.OwnResArticleMapper;
import com.apartment.own.domain.OwnResArticle;
import com.apartment.own.service.IOwnResArticleService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 物品Service业务层处理
 *
 * @author @Dog_E
 * @date 2020-08-28
 */
@Service
public class OwnResArticleServiceImpl extends ServiceImpl<OwnResArticleMapper, OwnResArticle> implements IOwnResArticleService {
    @Autowired
    private OwnResArticleMapper ownResArticleMapper;

    /**
     * 查询物品
     *
     * @param id 物品ID
     * @return 物品
     */
    @Override
    public OwnResArticle selectOwnResArticleById(Long id) {
        return ownResArticleMapper.selectOwnResArticleById(id);
    }

    /**
     * 查询物品列表
     *
     * @param ownResArticle 物品
     * @return 物品
     */
    @Override
    public List<OwnResArticle> selectOwnResArticleList(OwnResArticle ownResArticle) {
        return ownResArticleMapper.selectOwnResArticleList(ownResArticle);
    }

    /**
     * 新增物品
     *
     * @param ownResArticle 物品
     * @return 结果
     */
    @Override
    public int insertOwnResArticle(OwnResArticle ownResArticle) {
        ownResArticle.setCreateTime(DateUtils.getNowDate());
        return ownResArticleMapper.insertOwnResArticle(ownResArticle);
    }

    /**
     * 修改物品
     *
     * @param ownResArticle 物品
     * @return 结果
     */
    @Override
    public int updateOwnResArticle(OwnResArticle ownResArticle) {
        ownResArticle.setUpdateTime(DateUtils.getNowDate());
        return ownResArticleMapper.updateOwnResArticle(ownResArticle);
    }

    /**
     * 批量删除物品
     *
     * @param ids 需要删除的物品ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteOwnResArticleByIds(Long[] ids) {
        //数组->List
        List<String> list = new ArrayList<>(Arrays.asList(longToString(ids)));
        //查询要删除的物品
        List<OwnResArticle> needDeleteArticles = ownResArticleMapper.selectList(Wrappers.<OwnResArticle>lambdaQuery()
                .in(OwnResArticle::getId, list));
        //清空数组
        list.clear();
        needDeleteArticles.forEach(articles -> {
            list.add(articles.getId().toString());
        });
        //查询要删除的物品下是否还有分类子
        List<OwnResArticle> childArticles = ownResArticleMapper.selectList(Wrappers.<OwnResArticle>lambdaQuery()
                .in(OwnResArticle::getParentId, list));

        return childArticles.size() == 0 ?
                AjaxResult.success("删除条数: " + ownResArticleMapper.deleteOwnResArticleByIds(ids))
                : AjaxResult.error("所选中物品有子物品,无法删除");
    }


    public static String[] longToString(Long[] array){
        if(array == null || array.length == 0) return null;
        String[] strArr = new String[array.length];
        for(int i=0;i<strArr.length;i++){
            strArr[i] = String.valueOf(array[i]);
        }
        return strArr;
    }

    /**
     * 删除物品信息
     *
     * @param id 物品ID
     * @return 结果
     */
    @Override
    public int deleteOwnResArticleById(Long id) {
        return ownResArticleMapper.deleteOwnResArticleById(id);
    }


    /**
     * @param resArticleDTO: 物品对象DTO
     * @Description: 新增物品
     * @return: com.apartment.common.core.domain.AjaxResult
     * @Author: @Dog_E
     * @Date: 2020/9/4 0003
     **/
    @Override
    @Transactional
    public int addOwnResArticle(ResArticleDTO resArticleDTO) {
        //定义一个删除集合
        List<OwnResArticle> deleteList = new ArrayList<>();
        //1.取出resArrticleDTO中的集合
        //list 去重
        List<OwnResArticle> ownResArticles = new CollectionHelper<OwnResArticle>()
                .deduplicationList( resArticleDTO.getOwnResArticles(),"getItemsName");

        Map<String, OwnResArticle> hashMap = new HashMap<>();

        for (int i = 0; i < ownResArticles.size(); i++) {
            //判断名字是不是空是删除   或者   名字已经和数据库重复则删除
            if (StringUtils.isEmpty(ownResArticles.get(i).getItemsName()) || Objects.nonNull(ownResArticleMapper.selectSearchByItemName(ownResArticles.get(i).getItemsName()))) {
                //是添加到删除
                deleteList.add(ownResArticles.get(i));
            }
        }
        //删除与数据库中名字相同的对象和空名字对象
        ownResArticles.removeAll(deleteList);

        //数据库所有物品
        List<OwnResArticle> allItems = ownResArticleMapper.selectOwnResArticleList(null);
        hashMap.clear();
        //存放在hashMap里
        allItems.forEach(article -> {
            hashMap.put(article.getId().toString(), article);
        });

        ownResArticles.forEach(addArticle -> {
            //判断添加是否是父级物品
            //当物品对象父id为空时  设置等级
            if (addArticle.getParentId() == null || Long.valueOf(addArticle.getParentId()).longValue() < 1) {
                addArticle.setLevel(1);
            } else {
                OwnResArticle ownResArticle = hashMap.get(addArticle.getParentId());
                //等级加1
                if ((ownResArticle.getLevel() + 1)>=4) {
                    throw new CustomException("最多3级");
                }
                addArticle.setLevel(ownResArticle.getLevel() + 1);
            }
        });
        return saveBatch(ownResArticles) ? 1 : 0;
    }


    /**
     * @param resArticleDTO:
     * @Description: 物品级联查询
     * @return: java.util.List<com.apartment.own.request.res.ResArticleDTO>
     * @Author: @Dog_E
     * @Date: 2020/9/4 0004 10:27
     **/
    @Override
    public List<ResArticleDTO> cascadeQueryList(ResArticleDTO resArticleDTO) {
        //查询所有物品/条件查询
        List<ResArticleDTO> entities = ownResArticleMapper.selectResArticleDTOList(resArticleDTO);
        entities.forEach(e->{
            e.setLabel(e.getItemsName());
        });

        //2. 组装成父子的树形结构
        //2.1 找到所有一级分类
        List<ResArticleDTO> level1Menus = entities.stream().filter(categoryEntity -> {
            //查出一级分类后返回
            return categoryEntity.getParentId().equals("-1") ;
        }).map((menu) -> {
            //查出当前分类 的所有下级分类,set进去后返回
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).collect(Collectors.toList());

        return level1Menus;
    }

    private List<ResArticleDTO> getChildren(ResArticleDTO resArticleDTO, List<ResArticleDTO> all) {
        List<ResArticleDTO> entityList = all.stream().filter(category -> {
            return category.getParentId().equals(resArticleDTO.getId());
        }).map(menu -> {
            menu.setChildren(getChildren(menu, all));
            return menu;
        }).collect(Collectors.toList());
        return entityList;
    }

}
